//
//  Copyright (C) 2009 Vadim Ushakov
// 
//  This program is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License as published by the Free
//  Software Foundation; either version 2 of the License, or (at your option)
//  any later version.
// 
//  This program is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
//  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
//  for more details.
//  
//  You should have received a copy of the GNU General Public License along
//  with this program; if not, write to the Free Software Foundation, Inc.,
//  59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//


/*
<help>

 -- install-boot-code --

Install a boot code on the volume.

Usage:
  install-boot-code <boot code image> <disk>

The install-boot-code command copies the named boot code image to the named
disk. It is used, for example, by the installation program. It could also be
useful in a system rescue situation.

Example:
  install-boot-code /system/boot/bootsect-fat16 hd0

</help>
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <ailes/disk.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <sys/vsh.h>


static void usage(char *name)
{
	printf("usage:\n%s <boot image> <output file|device>\n", name);
	return;
}


int main(int argc, char *argv[])
{
	int status = 0;
	char *sourceName = NULL;
	char *destName = NULL;
	char fsType[FSTYPE_MAX_NAMELENGTH + 1];
	char command[MAX_PATH_NAME_LENGTH];

	if (argc != 3)
	{
		usage(argv[0]);
		errno = EINVAL;
		return (status = -1);
	}

	sourceName = argv[1];
	destName = argv[2];

	// Make sure we know the filesystem type
	status = diskGetFilesystemType(destName, fsType, FSTYPE_MAX_NAMELENGTH);

	if (status < 0)
	{
		printf("Unable to determine the filesystem type on disk \"%s\"", destName);
		return (status);
	}

	char* suffix = NULL;
	if (strncmp(fsType, "fat", 3) == 0)
		suffix = "fat";
	else
		suffix = fsType;

	// Use our companion program to do the work
	sprintf(command, "/programs/install-boot-code.%s %s %s", suffix, sourceName, destName);
	status = system(command);

	diskSync(destName);

	// Return success
	return (status);
}


